package conf

import (
	"pan/common/exception"
	"pan/common/util"
)

var GlobalConfig *Configure

type UrlPath struct {
	Login       string `json:"login"`
	Refresh     string `json:"refresh"`
	User        string `json:"user"`
	Docs        string `json:"docs"`
	DirList     string `json:"dirList"`
	Download    string `json:"download"`
	BeginUpload string `json:"beginUpload"`
	EndUpload   string `json:"endUpload"`
}

type Configure struct {
	// 日志级别
	LogLevel string `json:"logLevel"`
	// 服务器根路径
	Url string `json:"url"`
	// api接口路径
	Paths UrlPath `json:"paths"`
}

func (c *Configure) IsEmpty() bool {
	return c.Url == ""
}

func (c *Configure) Load(path string) error {
	if path == "" {
		path = util.ConfigFilePath()
	}
	if path == "" {
		return exception.NewExpectError("config not found")
	}
	configure := &Configure{}
	if err := util.LoadJsonFile(path, configure); err != nil {
		return err
	}
	c.copyProperties(configure)
	return nil
}

func (c *Configure) copyProperties(src *Configure) {
	if src.LogLevel != "" {
		c.LogLevel = src.LogLevel
	}
	if src.Url != "" {
		c.Url = src.Url
	}
	if src.Paths.Login != "" {
		c.Paths.Login = src.Paths.Login
	}
	if src.Paths.Refresh != "" {
		c.Paths.Refresh = src.Paths.Refresh
	}
	if src.Paths.User != "" {
		c.Paths.User = src.Paths.User
	}
	if src.Paths.Docs != "" {
		c.Paths.Docs = src.Paths.Docs
	}
	if src.Paths.DirList != "" {
		c.Paths.DirList = src.Paths.DirList
	}
	if src.Paths.Download != "" {
		c.Paths.Download = src.Paths.Download
	}
	if src.Paths.BeginUpload != "" {
		c.Paths.BeginUpload = src.Paths.BeginUpload
	}
	if src.Paths.EndUpload != "" {
		c.Paths.EndUpload = src.Paths.EndUpload
	}
}

func NewConfigure() *Configure {
	return &Configure{
		Url: "https://pan.syberos.com/api/v1",
		Paths: UrlPath{
			Login:       "/auth1/getnew",
			Refresh:     "/auth1/refreshtoken",
			User:        "/user/get",
			Docs:        "/entrydoc2/get",
			DirList:     "/dir/list",
			Download:    "/file/osdownload",
			BeginUpload: "/file/osbeginupload",
			EndUpload:   "/file/osendupload",
		},
	}
}
